
#include <cassert>
#include "HttpReply.h"


//const char* HELLO_WORLD_REPLY = _T("HTTP/1.0 200 OK\r\nContent-Length:84\r\n\r\n<html><body><h1>Hello World!</h1></body></html>");

HttpReply::HttpReply()
{
	_status_code = SC_INTERNAL_SERVER_ERROR;
	headers.set( "Content-Length", "0" );
	//headers.set( "Content-Type", "plain/text" );
}

HttpReply::~HttpReply()
{
}

void HttpReply::status_code(HttpStatusCode status_code)
{
	_status_code = status_code;
}

const char * httpStatusCodeString( const HttpStatusCode statusCode ){
	switch( statusCode ){
		case SC_NOT_IMPLEMENTED:
			return "Not Implemented";
		case SC_NOT_FOUND:
			return "Not Found";
		case SC_HTTP_VERSION_NOT_SUPPORTED:
			return "HTTP Version Not Supported";
		case SC_BAD_REQUEST:
			return "Bad Request";			
		case SC_OK:
			return "OK";
		case SC_INTERNAL_SERVER_ERROR:
			return "Internal Server Error";
		default:
			return "Unknown Status Code";
	}
}

void HttpReply::send( sock::TextSocket * psock )
{
	char buf[300];
	sprintf_s( buf, 300, "HTTP/%s %d %s", "1.0", _status_code, httpStatusCodeString(_status_code) );
	psock->writeln( buf );
	printf( "%s\n", buf );

	for( http::Headers::const_iterator it = headers.begin();
		it != headers.end();
		it++)
	{
		psock->writeln( it->first + ": " + it->second );
		printf( "%s\n", (it->first + ": " + it->second).c_str() );
	}
	psock->writeln( "" );
	send_body( *psock );
}
